package com.qf.service;

import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 路由策略
 * @author zhaojian
 */
@Service(value = "router")
@Slf4j
public class RouterFilterServiceImpl implements FilterChainService {


    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;//
    /**
     *
     * 路由策略
     * **路由 ：**从客户通道表中选择所匹配的通道下发
     *
     * - 如果找不到通道把发送日志存到Elasticsearch
     * - 如果同时是HTTP的发送方式就模拟出状态报告推送给客户
     *
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        try {
            //1:通道ID  channelId
            Integer gatewayID = standardSubmit.getGatewayID();
            //队列名称
            String queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + gatewayID;
            //2:动态创建队列     declare:声明   队列Queue
            amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
            //3:策略模块所有策略全部成功  发送对象到MQ中   中国移动  sms_send_gateway_1  中国联通 sms_send_gateway_2
            rabbitTemplate.convertAndSend(queueName,standardSubmit);
            // 交换机（默认）   --routingKey --> 队列  （简单模式）
        } catch (Exception e) {
            //
            log.error("[路由策略]...失败！！！");
            return false;
        }
        //路由成功
        return true;
    }
}